from flask import Flask, request, jsonify
from flask_cors import CORS
import os

from video import video_bp
from login import login_bp  # 导入 login_bp
from rag.file_splitting import file_rag_bp  # 导入 file_rag_bp

from constants import TOKEN  # 导入 TOKEN

app = Flask(__name__)

# 配置 CORS
CORS(app, resources={r"/api/*": {"origins": "*"}})

# 注册蓝图
app.register_blueprint(video_bp)
app.register_blueprint(login_bp)  # 注册 login_bp
app.register_blueprint(file_rag_bp, url_prefix="/rag")  # 注册 file_rag_bp

# Token 校验函数
def token_required(f):
    def decorator(*args, **kwargs):
        token = request.headers.get('Authorization')
        print(token)
        if not token or token != "Bearer " + TOKEN:
            return jsonify({'message': 'Token is missing or invalid!'}), 401
        return f(*args, **kwargs)
    return decorator

# 应用 token 校验到所有请求，排除 /login 路由
@app.before_request
def before_request():
    if request.endpoint != 'login.login':
        return token_required(lambda: None)()

if __name__ == '__main__':
    if not os.path.exists('temp'):
        os.makedirs('temp')
    if not os.path.exists('static'):
        os.makedirs('static')
    app.run(debug=True, port=5000)